<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Document</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css"/>
  <link rel="stylesheet" href="../../styles/common.css"/>
  <link rel="stylesheet" href="../../styles/page.css"/>
  <style>
    #combo-add-app .comboCommodity .el-form-item__label::before{
      content: '*';
      color: #F56C6C;
      margin-right: 4px;
    }
  </style>
</head>
<body>
  <div class="addBrand-container" id="combo-add-app">
    <div class="container">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        :inline="true"
        label-width="180px"
        class="demo-ruleForm"
      >
        <div>
          <el-form-item label="套餐名称" prop="name" >
            <el-input v-model.trim="ruleForm.name" placeholder="请填写套餐名称" maxlength="60" />
          </el-form-item>
          <el-form-item label="套餐分类" prop="categoryId">
            <el-select v-model="ruleForm.categoryId" placeholder="请选择套餐分类">
              <el-option v-for="(item,index) in comboCategoryList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="套餐价格" prop="price">
            <el-input v-model.trim="ruleForm.price" placeholder="请设置套餐价格" />
          </el-form-item>
        </div>
        <div>
          <el-form-item label="套餐商品" prop="commodities" class="comboCommodity">
            <el-form-item>
              <div class="CommodityBox">
                <el-button v-if="ruleForm.commodities.length==0" type="primary" @click="openDialog">+ 添加商品</el-button>
                <div v-if="ruleForm.commodities.length!=0" class="content">
                  <el-button type="primary" size="medium" @click="openDialog">重新选择</el-button>
                  <div class="table">
                    <el-table :data="ruleForm.commodities" style="width: 100%">
                      <el-table-column prop="commodityName" label="名称" align="center"></el-table-column>
                      <el-table-column label="价格" align="center">
                        <template slot-scope="scope">
                          ￥ {{scope.row.commodityPrice}}
                        </template>
                      </el-table-column>
                      <el-table-column label="份数" align="center">
                        <template slot-scope="scope">
                          <el-input-number v-model="scope.row.copies" :min="1" step-strictly size="small" />
                        </template>
                      </el-table-column>
                      <el-table-column label="操作" align="center">
                        <template slot-scope="scope">
                          <el-button type="text" size="small" @click="deleteCommodity(scope.$index)">删除</el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-form-item>
        </div>
        <el-form-item label="商品配置" prop="configs">
          <el-form-item>
            <div class="configBox">
              <el-button v-if="commodityConfigs.length==0" type="primary" @click="addConfigs">+ 添加配置</el-button>
              <div v-if="commodityConfigs.length!=0" class="config">
                <div class="tip">
                  <span>提示：输入标签回车添加</span>
                </div>
                <div class="configMain">
                  <div v-for="(item,index) in commodityConfigs" :key="index" class="items">
                    <div class="name">
                      <div class="selectInput">
                        <div>
                          <el-input v-model.trim="item.name" style="width: 100%" placeholder="配置名称" maxlength="60"
                                    @focus="item.showOption=true" @blur="item.showOption=false" />
                        </div>
                        <div v-show="item.showOption" class="configSelect">
                          <span v-for="(dataItem,dataIndex) in commodityConfigsData" :key="dataIndex" class="items"
                                @mousedown="selectOption(dataItem,index)">{{dataItem.name}}</span>
                        </div>
                      </div>
                    </div>
                    <div class="label">
                      <el-tag v-for="(labItem,labIndex) in item.value" :key="labIndex" class="tag"
                              closable @close="delConfigLabel(labIndex, index)">{{labItem}}</el-tag>
                      <div class="inputBox" :style="{flex: 1}" contenteditable="true"
                           @keydown.enter="(val)=>keyDownHandle(val,index)"></div>
                    </div>
                    <span class="delConfig delBut" @click="delConfig(index)">删除</span>
                  </div>
                </div>
                <el-button type="primary" @click="addConfigs">添加配置</el-button>
              </div>
            </div>
          </el-form-item>
        </el-form-item>
        <div>
          <el-form-item label="套餐图片" prop="image">
            <el-upload
              class="avatar-uploader"
              action="/api/common/upload"
              accept="image/*"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="successUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar"/>
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </div>
        <div class="address">
          <el-form-item label="套餐描述" prop="description">
            <el-input v-model="ruleForm.description" type="textarea" :rows="3"
                      placeholder="套餐描述，最长300字" maxlength="300" />
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-form-item>
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm',false)" :disabled="submitting">保存</el-button>
            <el-button type="primary" class="continue" @click="submitForm('ruleForm',true)" :disabled="submitting">保存并继续添加</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <el-dialog title="添加商品" :visible.sync="dialogVisible" :show-close="false" width="60%" class="addDialog"
               :close-on-click-modal="false">
      <el-input v-model.trim="searchValue" placeholder="请输入商品名称" size="small" class="search" clearable
                @keyup.enter.native="searchHandle">
        <i slot="prefix" class="el-input__icon el-icon-search" style="cursor: pointer" @click="searchHandle"></i>
      </el-input>
      <div class="addMain">
        <div class="leftPart">
          <div v-show="showCategoryTab" class="categoryTab">
            <span v-for="(item,index) in commodityCategoryList" :key="index" :class="{line:item.id==currCategoryId}"
                  @click="changeCategory(item.id)">{{item.name}}</span>
          </div>
          <div class="commodityTab">
            <div class="table">
              <div v-if="commodityList.length==0" style="text-align: center">暂无商品</div>
              <el-checkbox-group v-if="commodityList.length>0" v-model="checkListCache" @change="checkListHandle">
                <div v-for="(item,index) in commodityList" :key="index" class="items">
                  <el-checkbox :key="index" :label="JSON.stringify(item)">
                    <div class="item">
                      <span style="flex: 3;text-align: left">{{item.name}}</span>
                      <span>{{item.status == 0 ? '已停售' : '售卖中'}}</span>
                      <span>￥ {{item.price}}</span>
                    </div>
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </div>
          </div>
        </div>
        <div class="rightPart">
          <div>已选商品 ({{checkList.length}})</div>
          <div class="items">
            <div v-for="(item,index) in checkList" :key="index" class="item">
              <span class="name">{{item.name}}</span>
              <span class="price">￥ {{item.price}}</span>
              <span class="delete" @click="deleteCheck(index)">
                <i class="el-icon-circle-close"></i>
              </span>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="medium" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" size="medium" @click="addCommodity">确定</el-button>
      </span>
    </el-dialog>
  </div>
  <!-- 开发环境版本，包含了有帮助的命令行警告 -->
  <script src="../../plugins/vue/vue.js"></script>
  <!-- 引入组件库 -->
  <script src="../../plugins/element-ui/index.js"></script>
  <!-- 引入axios -->
  <script src="../../plugins/axios/axios.min.js"></script>
  <script src="../../js/request.js"></script>
  <script src="../../js/common.js"></script>
  <script src="../../api/category.js"></script>
  <script src="../../api/commodity.js"></script>
  <script src="../../api/combo.js"></script>
  <script>
    new Vue({
      el: '#combo-add-app',
      data() {
        return {
          dialogVisible: false,
          searchValue: '',
          showCategoryTab: true,
          currCategoryId: 0,
          comboCategoryList: [],
          commodityCategoryList: [],
          commodityList: [],
          checkListCache: [],
          checkList: [],
          commodityConfigsData: [],
          commodityConfigs: [],
          imageUrl: '',
          ruleForm: {
            name: '',
            categoryId: '',
            price: '',
            image: '',
            description: '',
            commodities: [],
            configs: []
          },
          submitting: false
        }
      },
      computed: {
        rules() {
          const checkPrice = (rule, value, callback) => {
            let reg = /^\d+(\.\d{0,2})?$/
            if (value.length < 1) {
              callback(new Error('请设置套餐价格'))
            } else if (!reg.test(value)) {
              callback(new Error('价格只能为数字,且最多保留两位小数'))
            } else if (value > 99999999.99) {
              callback(new Error('价格过大'))
            } else {
              callback()
            }
          }
          return {
            name: [{required: true, message: '请填写套餐名称', trigger: 'blur'}],
            categoryId: [{required: true, message: '请选择套餐分类', trigger: 'change'}],
            price: [{required: true, validator: checkPrice, trigger: 'blur'}]
          }
        },
      },
      created() {
        this.getComboCategoryList()
        this.getCommodityCategoryList()
        this.commodityConfigsData = getConfigListHand()
      },
      methods: {
        // 获取套餐分类
        getComboCategoryList() {
          getCategoryListApi({type: 1}).then(res => {
            this.comboCategoryList = res.data
          }).catch(error => {
            this.$message.error(error.message)
          })
        },
        // 获取商品分类
        getCommodityCategoryList() {
          getCategoryListApi({type: 0}).then(res => {
            this.commodityCategoryList = res.data
          }).catch(error => {
            this.$message.error(error.message)
          })
        },

        // 根据参数获取商品信息，并后续执行相关操作
        getCommoditiesByParams(params, func) {
          getCommodityListApi(params).then(res => {
            this.commodityList = res.data
            if (typeof func === 'function') {
              func()
            }
          }).catch(error => {
            this.$message.error(error.message)
          })
        },
        // 按钮 - 打开添加商品弹框
        openDialog() {
          this.searchValue = ''
          this.showCategoryTab = true
          this.checkListCache = []
          this.checkList = []
          this.currCategoryId = this.commodityCategoryList[0].id
          this.getCommoditiesByParams({categoryId: this.currCategoryId}, () => {
            this.dialogVisible = true
          })
        },
        // 根据商品名称关键字查找商品信息
        searchHandle() {
          if (this.searchValue) {
            this.getCommoditiesByParams({name: this.searchValue}, () => {
              this.showCategoryTab = false
            })
          } else {
            this.getCommoditiesByParams({categoryId: this.currCategoryId}, () => {
              this.showCategoryTab = true
            })
          }
        },
        // 切换商品分类
        changeCategory(id) {
          this.currCategoryId = id
          this.getCommoditiesByParams({categoryId: id})
        },
        // 预选中商品
        checkListHandle(value) {
          this.checkList = value.map(v => JSON.parse(v))
        },
        // 删除已预选中商品
        deleteCheck(index) {
          this.checkListCache.splice(index, 1)
          this.checkList.splice(index, 1)
        },
        // 保存选中的商品
        addCommodity() {
          this.ruleForm.commodities = this.checkList.map(commodity => ({
            commodityId: commodity.id,
            commodityName: commodity.name,
            commodityPrice: commodity.price,
            copies: 1
          }))
          this.dialogVisible = false
        },
        // 删除已选中的商品
        deleteCommodity(index) {
          this.ruleForm.commodities.splice(index, 1)
        },

        // 按钮 - 添加配置项
        addConfigs() {
          this.commodityConfigs.push({name: '', value: [], showOption: false})
        },
        // 按钮 - 删除配置项
        delConfig(index) {
          this.commodityConfigs.splice(index, 1)
        },
        // 选中 - 配置选项
        selectOption(dataItem, index) {
          this.commodityConfigs[index].name = dataItem.name
          this.commodityConfigs[index].value = JSON.parse(JSON.stringify(dataItem.value))
        },
        // 按钮 - 删除配置标签
        delConfigLabel(labIndex, index) {
          this.commodityConfigs[index].value.splice(labIndex, 1)
        },
        // 按下回车 - 添加配置标签
        keyDownHandle(val, index) {
          if (event) {
            event.cancelBubble = true
            event.preventDefault()
            event.stopPropagation()
          }
          if (val.target.innerText.trim() !== '') {
            this.commodityConfigs[index].value.push(val.target.innerText)
            val.target.innerText = ''
          }
        },

        // 提交表单
        submitForm(formName, st) {
          this.submitting = true
          this.$refs[formName].validate((valid) => {
            if (valid) {
              if (this.ruleForm.commodities.length < 1) {
                this.$message.error('请添加套餐商品')
                return false
              }
              for (let commodity of this.ruleForm.commodities) {
                if (!commodity.copies) {
                  this.$message.error('请设置商品的份数')
                  return false
                }
              }
              const params = {...this.ruleForm}
              params.configs = JSON.parse(JSON.stringify(this.commodityConfigs))
              params.configs.forEach(config => {
                config.value = `[${config.value.toString()}]`  // 把配置标签数组转换为字符串形式
                delete config.showOption  // 删除无关属性
              })
              addComboApi(params).then(res => {
                window.parent.$message.success('添加成功')
                if (!st) {
                  this.goBack()
                } else {
                  let currCategoryId = this.ruleForm.categoryId
                  this.imageUrl = ''
                  this.commodityConfigs = []
                  this.$refs[formName].resetFields()
                  this.ruleForm.categoryId = currCategoryId
                }
                this.submitting = false
              }).catch(error => {
                this.$message.error(`${error.message}，添加失败`)
                this.submitting = false
              })
            } else {
              this.submitting = false
              return false
            }
          })
        },

        // 文件上传前对格式和大小进行检查
        beforeUpload(file) {
          const isImage = file.type.startsWith("image/")
          const isLt2M = file.size / 1024 / 1024 <= 2
          if (!isImage) {
            this.$message.error('仅支持图片文件')
          }
          if (!isLt2M) {
            this.$message.error('图片大小不能超过2MB')
          }
          return isImage && isLt2M
        },
        // 文件上传成功
        successUpload(res, file) {
          if (res.code === 20000) {
            this.imageUrl = URL.createObjectURL(file.raw)  // 赋值图片的url，用于图片回显功能
            this.ruleForm.image = res.data
          } else {
            this.$message.error(`${res.message}，图片上传失败`)
          }
        },

        goBack() {
          window.parent.menuHandle({
            id: '4',
            url: '/backend/page/combo/list.html',
            name: '套餐管理',
          }, false)
        }
      }
    })
  </script>
</body>
</html>
